//
//  HomePageViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/3/29.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "HomePageViewController.h"
#import "AFNetworking.h"
#import "NetStatusHandle.h"
#import "SDCycleScrollView.h"
#import "ZiXunTableViewCell.h"
#import "ShiLiBaoGaoViewController.h"
#import "ZiXunViewController.h"
#import "ZiXunModel.h"
#import "LeiModelOnHomePage.h"
#import "MoreZiXunViewController.h"
#import "HJCarouselViewLayout.h"
#import "GouMaiLiuChengCollectionViewController.h"
#import "OnLineProductViewController.h"
#import "ProductDetailViewController.h"
#import "MJRefresh.h"
#import <AVFoundation/AVFoundation.h>
#import "QRCodeController.h"
#import "AppDelegate.h"
#import <RongIMKit/RongIMKit.h>
#import "ProductViewController.h"



// 梅江林
#import "ShowDaySignInViewController.h"
#import "HomeTradeTraceViewController.h"
#import "SaoYiSaoResultViewController.h"

#define kShouYeUrl @"http://120.26.129.84/api/home"
#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface HomePageViewController ()<UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, strong) UITableView *homePageTableView;

@property (nonatomic, strong) NSMutableArray *homePageScrollViewImageArray; // 轮播图数组
@property (nonatomic, strong) NSMutableArray *homePageScrollViewUrlArray; // 轮播图链接数组
@property (nonatomic, strong) NSMutableArray *onLineProductNameArray; // 上线产品的名字

@property (nonatomic, strong) NSMutableArray *ziXunDataArray; // 咨询数组
@property (nonatomic, strong) NSMutableArray *leiMingDataArray; // 类名数组

@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间


//梅江林
@property(nonatomic,assign)BOOL gotoShowDaySignInViewController;
@end

@implementation HomePageViewController

- (void)viewWillAppear:(BOOL)animated
{
    
//    self.homePageTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden=NO;
//    NSLog(@"高度 = %f", self.homePageTableView.height);
    
    //梅江林
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
    if (!_gotoShowDaySignInViewController) {
        [self getSuperSignInHttpData];
    }else{
        //签到失败，开始准备后一天的签到
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        NSString *lastSignTime=[user objectForKey:@"lastSignTime"];
        if (lastSignTime==nil) {
            return;
        }
        NSInteger days=[self getDays:lastSignTime];
        if (days>0) {
            [self getSuperSignInHttpData];
        }else{
            
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    // 关闭动画
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    // 关闭计时器
    [self.myTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"首页";
    // 判断网络
    [self netStatus];
    // 改变navigation
    [self changePage];
    // 布局
    [self addMySubview];
    
    // 检查网络并建立数据源
    [self searchNetAndAddData];
    
}

// 判断网络状态
- (void)netStatus
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // AFNetworkReachabilityStatusUnknown          = -1, // 不可知
        //        AFNetworkReachabilityStatusNotReachable     = 0, // 无网络
        //        AFNetworkReachabilityStatusReachableViaWWAN = 1, // 2d或者3d
        //        AFNetworkReachabilityStatusReachableViaWiFi = 2, // wifi
        NetStatusHandle *handle = [NetStatusHandle shareHandle];
        if (status == 0) {
            // 无网络
            NSLog(@"没有网络");
            [handle saveNetStatus:@"NO"];
            NSLog(@"网络状态：%@", [handle getNetStatus]);
        } else {
            // 有网络
            NSLog(@"有网络");
            [handle saveNetStatus:@"YES"];
            NSLog(@"网络状态：%@", [handle getNetStatus]);
        }
    }];
}

#pragma mark - 改变配置
- (void)changePage
{
    self.navigationItem.title = @"首页";
    [self.navigationController.navigationBar setTranslucent:NO];
    // iOS7.0以后需要这样设置
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:22]};
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1]];
    
    
}

#pragma mark - 检查网络并建立数据源
- (void)searchNetAndAddData
{
    self.homePageTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
      //  [[SDImageCache sharedImageCache] clearDisk];
        // 判断网络
        if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
            // 说明有网络
            // 建立数据源
            [self addData];
            // 建立计时器，计算是否超时
            self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnHome:) userInfo:nil repeats:YES];
            //   [self.myTimer fire];
            [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
            self.numberOfTime = 0;
            // 开始动画
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
        } else {
            // 没网络
            NSLog(@"没网络");
            // 添加提示框
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetRefresh ToView:self];
            // 停止刷新
            [self.homePageTableView.header endRefreshing];
        }
    }];
    [self.homePageTableView.header beginRefreshing];
}

#pragma mark - 计时器方法
- (void)goTimeOnHome:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"首页请求时间= %ld", self.numberOfTime);
    if (self.numberOfTime > 10) {
        NSLog(@"请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭刷新
        [self.homePageTableView.header endRefreshing];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiReFresh ToView:self];
    }
}

#pragma mark - 请求数据
- (void)addData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:kShouYeUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (!responseObject) {
            return;
        }
        // 关闭刷新
        [self.homePageTableView.header endRefreshing];
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        
        // 轮播图
        NSArray *productArray = [responseObject valueForKey:@"productions"];
        // 轮播图数组、链接初始化
        self.homePageScrollViewImageArray = [NSMutableArray array];
        self.homePageScrollViewUrlArray = [NSMutableArray array];
        // 上线产品名字初始化
        self.onLineProductNameArray = [NSMutableArray array];
        for (NSDictionary *tempDic in productArray) {
            [self.homePageScrollViewUrlArray addObject:[tempDic valueForKey:@"id"]];
            
            NSString *imageUrl = [[tempDic valueForKey:@"image_url"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [self.homePageScrollViewImageArray addObject:imageUrl];
            [self.onLineProductNameArray addObject:[tempDic valueForKey:@"name"]];
        }
        
        // 咨询
        NSArray *newsArray = [responseObject valueForKey:@"news"];
        self.ziXunDataArray = [NSMutableArray array];
        for (NSDictionary *tempDic in newsArray) {
            ZiXunModel *model = [[ZiXunModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.ziXunDataArray addObject:model];
        }
        
        // 类名
        NSArray *classificationsArray = [responseObject valueForKey:@"classifications"];
        self.leiMingDataArray = [NSMutableArray array];
        for (NSDictionary *tempDic in classificationsArray) {
            LeiModelOnHomePage *model = [[LeiModelOnHomePage alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.leiMingDataArray addObject:model];
        }
        // 重新布局
        [self addTableViewHeaderView];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"数据获取失败");
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiRefresh ToView:self];
        // 停止刷新
        [self.homePageTableView.header endRefreshing];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;
    }];
}

#pragma mark - 布局
- (void)addMySubview
{
    self.homePageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 49) style:UITableViewStylePlain];
    self.homePageTableView.dataSource = self;
    self.homePageTableView.delegate = self;
    self.homePageTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_homePageTableView];
    //   self.homePageTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self addTableViewHeaderView];
}
#pragma mark - 构建tableView表头
- (void)addTableViewHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 545 * kAdjustParamater)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.homePageTableView.tableHeaderView = headerView;
    
#warning 如果感觉高度不够的话可以更改，现在是175
    // 轮播图
    SDCycleScrollView *scrollerIVew = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 175 * kAdjustParamater) imageURLStringsGroup:self.homePageScrollViewImageArray];
    scrollerIVew.pageControlDotSize = CGSizeMake(5 * kAdjustParamater, 5 * kAdjustParamater);
    scrollerIVew.currentPageDotColor = kCyanColor;
    scrollerIVew.pageDotColor = [UIColor whiteColor];
    scrollerIVew.delegate = self;
    [headerView addSubview:scrollerIVew];
    
    // 渐变背景图
    UIImageView *jianBianGroundImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, scrollerIVew.bottom, kScreenWidth, 200 * kAdjustParamater)];
    jianBianGroundImageV.image = [UIImage imageNamed:@"jianbianbeijingtu-shouye"];
    jianBianGroundImageV.userInteractionEnabled = YES;
    [headerView addSubview:jianBianGroundImageV];
    
    // 添加更多类按钮
    UILabel *leiMoreLabel = [[UILabel alloc] initWithFrame:CGRectMake((375 - 61) * kAdjustParamater, 7 * kAdjustParamater, 30 * kAdjustParamater, 14 * kAdjustParamater)];
    //  moreLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    leiMoreLabel.text = @"更多";
    leiMoreLabel.textColor = [UIColor blackColor];
    leiMoreLabel.userInteractionEnabled = YES;
    leiMoreLabel.textAlignment = NSTextAlignmentCenter;
    leiMoreLabel.font = [UIFont systemFontOfSize:k14Big];
    [jianBianGroundImageV addSubview:leiMoreLabel];
    
    UITapGestureRecognizer *moreTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreLeiGes:)];
    [leiMoreLabel addGestureRecognizer:moreTapGes];

    
    // 类更多的图片
    UIImageView *leiMoreImageV = [[UIImageView alloc] initWithFrame:CGRectMake(leiMoreLabel.right + 4 * kAdjustParamater, 0, 28 * kAdjustParamater, 28 * kAdjustParamater)];
    leiMoreImageV.image = [UIImage imageNamed:@"gengduo-shouye"];
    leiMoreImageV.userInteractionEnabled = YES;
    [jianBianGroundImageV addSubview:leiMoreImageV];
    
    UITapGestureRecognizer *moreImageTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreLeiImageGes:)];
    [leiMoreImageV addGestureRecognizer:moreImageTapGes];
    
    // 构建八大病
    for (int i = 0; i < 8; i++) {
        
        UIImageView *tempImageV = [[UIImageView alloc] initWithFrame:CGRectMake(32 * kAdjustParamater + (i % 4) * (50 + 40) * kAdjustParamater, 33 * kAdjustParamater + (i / 4) * (37 + 40) * kAdjustParamater, 40 * kAdjustParamater, 40 * kAdjustParamater)];
        tempImageV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        tempImageV.tag = 200 + i;
        tempImageV.userInteractionEnabled = YES;
        [jianBianGroundImageV addSubview:tempImageV];
        
        UITapGestureRecognizer *imageVTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageV:)];
        [tempImageV addGestureRecognizer:imageVTapGes];
        
        // 名称
        UILabel *diseaseNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(tempImageV.left - 23 * kAdjustParamater, tempImageV.bottom + 5 * kAdjustParamater, 86 * kAdjustParamater, 13 * kAdjustParamater)];
        //    diseaseNameLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        diseaseNameLabel.font = [UIFont systemFontOfSize:k14Big];
        diseaseNameLabel.textAlignment = NSTextAlignmentCenter;
        [jianBianGroundImageV addSubview:diseaseNameLabel];
        // 取出类model
        if (self.leiMingDataArray.count > i) {
            LeiModelOnHomePage *tempModel = self.leiMingDataArray[i];
            [tempImageV sd_setImageWithURL:[NSURL URLWithString:tempModel.icon_url] placeholderImage:[UIImage imageNamed:@""]];
            diseaseNameLabel.text = tempModel.name;
        }
    }
    
    // 八大病下方的灰色条
    UILabel *grayLineOnDiseaseBottom = [[UILabel alloc] initWithFrame:CGRectMake(0, jianBianGroundImageV.bottom, kScreenWidth, 10 * kAdjustParamater)];
    grayLineOnDiseaseBottom.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05];
    [headerView addSubview:grayLineOnDiseaseBottom];
    
    // 流程介绍图片
    UIImageView *liuChengJieShaoImageV = [[UIImageView alloc] initWithFrame:CGRectMake(12 * kAdjustParamater, grayLineOnDiseaseBottom.bottom + 7 * kAdjustParamater, 14 * kAdjustParamater, 14 * kAdjustParamater)];
    liuChengJieShaoImageV.image = [UIImage imageNamed:@"liuichengjieshao-shouye"];
    [headerView addSubview:liuChengJieShaoImageV];
    
    // 流程介绍标题
    UILabel *liuChengJieShaoTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(liuChengJieShaoImageV.right + 4 * kAdjustParamater, liuChengJieShaoImageV.top - 1 * kAdjustParamater, 65 * kAdjustParamater, 16 * kAdjustParamater)];
    //  liuChengJieShaoTitleLable.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    liuChengJieShaoTitleLable.text = @"流程介绍";
    liuChengJieShaoTitleLable.textColor = [UIColor blackColor];
    liuChengJieShaoTitleLable.textAlignment = NSTextAlignmentCenter;
    liuChengJieShaoTitleLable.font = [UIFont systemFontOfSize:k16Big];
    [headerView addSubview:liuChengJieShaoTitleLable];
    
    // 流程介绍右边的灰色箭头
    UIImageView *liuchengRightJianTouImageV = [[UIImageView alloc] initWithFrame:CGRectMake(liuChengJieShaoTitleLable.right + 16 * kAdjustParamater, liuChengJieShaoTitleLable.top, 30 * kAdjustParamater, 16 * kAdjustParamater)];
    liuchengRightJianTouImageV.image = [UIImage imageNamed:@"jianbianjiantou-shouye"];
    [headerView addSubview:liuchengRightJianTouImageV];
    
    // 购买流程图片
    UIImageView *gouMaiLiuChengImageV = [[UIImageView alloc] initWithFrame:CGRectMake(23 * kAdjustParamater, grayLineOnDiseaseBottom.bottom + 45 * kAdjustParamater, 57 * kAdjustParamater, 57 * kAdjustParamater)];
    gouMaiLiuChengImageV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    gouMaiLiuChengImageV.image = [UIImage imageNamed:@"首页购买流程图标-01"];
    gouMaiLiuChengImageV.layer.cornerRadius = gouMaiLiuChengImageV.width / 2;
    gouMaiLiuChengImageV.layer.masksToBounds = YES;
    gouMaiLiuChengImageV.userInteractionEnabled = YES;
    [headerView addSubview:gouMaiLiuChengImageV];
    
    UITapGestureRecognizer *gouMaiLiuChengTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gouMaiLiuChengGes:)];
    [gouMaiLiuChengImageV addGestureRecognizer:gouMaiLiuChengTapGes];
    
    // 购买流程标题
    UILabel *gouMalLiuChengLabel = [[UILabel alloc] initWithFrame:CGRectMake(gouMaiLiuChengImageV.left - 4 * kAdjustParamater, gouMaiLiuChengImageV.bottom + 17 * kAdjustParamater, 65 * kAdjustParamater, 16 * kAdjustParamater)];
    //   gouMalLiuChengLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    gouMalLiuChengLabel.text = @"购买流程";
    gouMalLiuChengLabel.textColor = [UIColor blackColor];
    gouMalLiuChengLabel.textAlignment = NSTextAlignmentCenter;
    gouMalLiuChengLabel.font = [UIFont systemFontOfSize:k15Big];
    [headerView addSubview:gouMalLiuChengLabel];
    
    // 购买流程右边的箭头
    UIImageView *jianTouInGouMaiLiuChengRight = [[UIImageView alloc] initWithFrame:CGRectMake(gouMaiLiuChengImageV.right + 8 * kAdjustParamater, gouMaiLiuChengImageV.top + 22 * kAdjustParamater, 63 * kAdjustParamater, 12 * kAdjustParamater)];
    jianTouInGouMaiLiuChengRight.image = [UIImage imageNamed:@"首页购买流程图标-05"];
    [headerView addSubview:jianTouInGouMaiLiuChengRight];
    
    // 示例报告图片
    UIImageView *shiLiBaoGaoImageV = [[UIImageView alloc] initWithFrame:CGRectMake(jianTouInGouMaiLiuChengRight.right + 8 * kAdjustParamater, gouMaiLiuChengImageV.top, 57 * kAdjustParamater, 57 * kAdjustParamater)];
    shiLiBaoGaoImageV.image = [UIImage imageNamed:@"首页购买流程图标-02"];
    shiLiBaoGaoImageV.userInteractionEnabled = YES;
    [headerView addSubview:shiLiBaoGaoImageV];
    
    UITapGestureRecognizer *shiLiBaoGaoTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shiLiBaoGaoGes:)];
    [shiLiBaoGaoImageV addGestureRecognizer:shiLiBaoGaoTapGes];
    
    // 示例报告标题
    UILabel *shiLiBaoGaoLabel = [[UILabel alloc] initWithFrame:CGRectMake(shiLiBaoGaoImageV.left - 4 * kAdjustParamater, shiLiBaoGaoImageV.bottom + 17 * kAdjustParamater, 65 * kAdjustParamater, 16 * kAdjustParamater)];
    shiLiBaoGaoLabel.text = @"示例报告";
    shiLiBaoGaoLabel.textColor = [UIColor blackColor];
    shiLiBaoGaoLabel.textAlignment = NSTextAlignmentCenter;
    shiLiBaoGaoLabel.font = [UIFont systemFontOfSize:k15Big];
    [headerView addSubview:shiLiBaoGaoLabel];
    
    // 示例报告右边的箭头
    UIImageView *jianTouInShiLiBaoGaoRight = [[UIImageView alloc] initWithFrame:CGRectMake(shiLiBaoGaoImageV.right + 8 * kAdjustParamater, shiLiBaoGaoImageV.top + 22 * kAdjustParamater, 63 * kAdjustParamater, 12 * kAdjustParamater)];
    jianTouInShiLiBaoGaoRight.image = [UIImage imageNamed:@"首页购买流程图标-05"];
    [headerView addSubview:jianTouInShiLiBaoGaoRight];
    
    // 订单跟踪图片
    UIImageView *dingDanGenZongImageV = [[UIImageView alloc] initWithFrame:CGRectMake(jianTouInShiLiBaoGaoRight.right + 8 * kAdjustParamater, gouMaiLiuChengImageV.top, 57 * kAdjustParamater, 57 * kAdjustParamater)];
    dingDanGenZongImageV.image = [UIImage imageNamed:@"首页购买流程图标-03"];
    dingDanGenZongImageV.userInteractionEnabled = YES;
    [headerView addSubview:dingDanGenZongImageV];
    
    UITapGestureRecognizer *dingDanGenZongTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dingDanGenZongGes:)];
    [dingDanGenZongImageV addGestureRecognizer:dingDanGenZongTapGes];
    
    // 订单跟踪标题
    UILabel *dingDanGenZongLabel = [[UILabel alloc] initWithFrame:CGRectMake(dingDanGenZongImageV.left - 4 * kAdjustParamater, dingDanGenZongImageV.bottom + 17 * kAdjustParamater, 65 * kAdjustParamater, 16 * kAdjustParamater)];
    dingDanGenZongLabel.text = @"订单跟踪";
    dingDanGenZongLabel.textColor = [UIColor blackColor];
    dingDanGenZongLabel.textAlignment = NSTextAlignmentCenter;
    dingDanGenZongLabel.font = [UIFont systemFontOfSize:k15Big];
    [headerView addSubview:dingDanGenZongLabel];
    
    // 流程介绍下方的灰色条
    UILabel *grayLineOnLiuChengJieShaoBottom = [[UILabel alloc] initWithFrame:CGRectMake(0, headerView.height - 10 * kAdjustParamater, kScreenWidth, 10 * kAdjustParamater)];
    grayLineOnLiuChengJieShaoBottom.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05];
    [headerView addSubview:grayLineOnLiuChengJieShaoBottom];
    
}

#pragma mark - 点击图片
- (void)clickImageV:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"点击的%ld个疾病", tapGes.view.tag - 200);
    if (self.leiMingDataArray.count > (tapGes.view.tag-200)) {
         LeiModelOnHomePage *model = self.leiMingDataArray[tapGes.view.tag - 200];
        if ([model.is_activate isEqualToString:@"1"]) {
            // 说明开放
            ProductDetailViewController *productDetailVC = [[ProductDetailViewController alloc] init];
            if (self.leiMingDataArray.count > (tapGes.view.tag - 200)) {
                
                productDetailVC.leiIDString = [NSString stringWithFormat:@"%@", model.myID];
            }
            [self.navigationController pushViewController:productDetailVC animated:YES];
        } else if ([model.is_activate isEqualToString:@"0"]) {
            // 说明不开放
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提醒" Content:@"此类暂未开放" ToView:self];
        }
    }
    
}

#pragma mark - 购买流程
- (void)gouMaiLiuChengGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"购买流程");
    HJCarouselViewLayout *layout = [[HJCarouselViewLayout alloc]initWithAnim:HJCarouselAnimLinear];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(kScreenWidth + 20 * kAdjustParamater, kScreenHeight - 40 * kAdjustParamater);
    GouMaiLiuChengCollectionViewController *gouMaiLiuChengCVC = [[GouMaiLiuChengCollectionViewController alloc] initWithCollectionViewLayout:layout];
    [self.navigationController pushViewController:gouMaiLiuChengCVC animated:YES];
}

#pragma mark - 示例报告
- (void)shiLiBaoGaoGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"示例报告");
    // 判断用户是否登录
    if ([NSString stringWithFormat:@"%@", kCurrentUserToken].length == 6 || [kCurrentUserToken isEqualToString:@"(null)"]) {
        // 没登录
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"示例报告必须登录以后才能查看，您现在要登录么" preferredStyle:UIAlertControllerStyleAlert];
        // 修改标题颜色
        NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"温馨提示"];
        [titleString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];
        [titleString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 4)];
        [alertVC setValue:titleString forKey:@"attributedTitle"];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
            [delegate showMainViewController:0];
        }];
        [alertVC addAction:sureAction];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {
        ShiLiBaoGaoViewController *shiLiBaoGaoVC = [[ShiLiBaoGaoViewController alloc] init];
        shiLiBaoGaoVC.haveZongHeBaoGao = NO;
        // shiLiBaoGaoVC.isShiLiBaoGao = YES;
        shiLiBaoGaoVC.isShiLiBaoGaoFormServer = YES;
        shiLiBaoGaoVC.userName = @"我";
        [self.navigationController pushViewController:shiLiBaoGaoVC animated:YES];
    }
   
}

#pragma mark - 订单跟踪
- (void)dingDanGenZongGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"订单跟踪");
    HomeTradeTraceViewController *vc=[HomeTradeTraceViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

#pragma mark - 类更多
- (void)moreLeiGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"更多类");
    ProductViewController *homePageVC = [[ProductViewController alloc] init];
    homePageVC.isJump = YES;
    homePageVC.shouldJumpLei = YES;
    [self.navigationController pushViewController:homePageVC animated:YES];
}

- (void)moreLeiImageGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"更多类的图片");
    ProductViewController *homePageVC = [[ProductViewController alloc] init];
    homePageVC.isJump = YES;
    homePageVC.shouldJumpLei = YES;
    [self.navigationController pushViewController:homePageVC animated:YES];
}

#pragma mark - 咨询更多
- (void)moreGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"更多咨询");
    MoreZiXunViewController *moreZiXunVC = [[MoreZiXunViewController alloc] init];
    [self.navigationController pushViewController:moreZiXunVC animated:YES];
}

- (void)moreImageGes:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"更多咨询");
    MoreZiXunViewController *moreZiXunVC = [[MoreZiXunViewController alloc] init];
    [self.navigationController pushViewController:moreZiXunVC animated:YES];
}

#pragma mark - 选中图片执行
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (self.homePageScrollViewUrlArray.count > index) {
        NSLog(@"点击了index = %ld", index);
        NSLog(@"包链接 = %@", self.homePageScrollViewUrlArray[index]);
        OnLineProductViewController *onLineProductVC = [[OnLineProductViewController alloc] init];
        onLineProductVC.onLineProductID = [NSString stringWithFormat:@"%@",self.homePageScrollViewUrlArray[index]];
        onLineProductVC.onLineProductName = self.onLineProductNameArray[index];
        [self.navigationController pushViewController:onLineProductVC animated:YES];
    }
    
}

#pragma mark - tableview代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ziXun";
    //    ZiXunTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //    if (cell == nil) {
    //        cell = [[ZiXunTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    //    }
    ZiXunTableViewCell *cell = [[ZiXunTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    NSLog(@"初始化前indexPath.row = %ld", indexPath.row);

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.ziXunDataArray.count > indexPath.row) {
        NSLog(@"indexPath.row = %ld", indexPath.row);
        cell.model = self.ziXunDataArray[indexPath.row];
    }
    return cell;
}

#pragma mark - 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了%ld行", indexPath.row);
    ZiXunViewController *ziXunVC = [[ZiXunViewController alloc] init];
    if (self.ziXunDataArray.count > indexPath.row) {
        ZiXunModel *tempModel = self.ziXunDataArray[indexPath.row];
        ziXunVC.ziXunID = [NSString stringWithFormat:@"%@", tempModel.myZiXunId];
    }
    [self.navigationController pushViewController:ziXunVC animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 28 * kAdjustParamater)];
    backGroundView.backgroundColor = [UIColor colorWithRed:148 / 255.0 green:208 / 255.0 blue:234 / 255.0 alpha:1];
    // 咨询图片
    UIImageView *ziXunImageV = [[UIImageView alloc] initWithFrame:CGRectMake(12 * kAdjustParamater, 7 * kAdjustParamater, 14 * kAdjustParamater, 14 * kAdjustParamater)];
    ziXunImageV.image = [UIImage imageNamed:@"zixun-shouye"];
    [backGroundView addSubview:ziXunImageV];
    
    // 咨询标题
    UILabel *ziXunLabel = [[UILabel alloc] initWithFrame:CGRectMake(ziXunImageV.right + 4 * kAdjustParamater,  6 * kAdjustParamater, 50 * kAdjustParamater, 16 * kAdjustParamater)];
    // ziXunLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    ziXunLabel.text = @"咨询";
    ziXunLabel.textColor = [UIColor blackColor];
    ziXunLabel.textAlignment = NSTextAlignmentLeft;
    ziXunLabel.font = [UIFont systemFontOfSize:k16Big];
    [backGroundView addSubview:ziXunLabel];
    
    // 更多
    UILabel *moreLabel = [[UILabel alloc] initWithFrame:CGRectMake((375 - 61) * kAdjustParamater, 7 * kAdjustParamater, 30 * kAdjustParamater, 14 * kAdjustParamater)];
    //  moreLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    moreLabel.text = @"更多";
    moreLabel.textColor = [UIColor blackColor];
    moreLabel.userInteractionEnabled = YES;
    moreLabel.textAlignment = NSTextAlignmentCenter;
    moreLabel.font = [UIFont systemFontOfSize:k14Big];
    [backGroundView addSubview:moreLabel];
    
    UITapGestureRecognizer *moreTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreGes:)];
    [moreLabel addGestureRecognizer:moreTapGes];
  
    
    // 更多图片
    UIImageView *moreImageV = [[UIImageView alloc] initWithFrame:CGRectMake(moreLabel.right + 4 * kAdjustParamater, 0, 28 * kAdjustParamater, 28 * kAdjustParamater)];
    moreImageV.image = [UIImage imageNamed:@"gengduo-shouye"];
    moreImageV.userInteractionEnabled = YES;
    [backGroundView addSubview:moreImageV];
    
    UITapGestureRecognizer *moreImageTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreImageGes:)];
    [moreImageV addGestureRecognizer:moreImageTapGes];
    
    return backGroundView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 28 * kAdjustParamater;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85 * kAdjustParamater;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10 * kAdjustParamater)];
//    footerView.backgroundColor = [UIColor redColor];
//    return footerView;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 0.1 * kAdjustParamater;
//}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat height = scrollView.frame.size.height;
    CGFloat contentYOffset = scrollView.contentOffset.y;
    CGFloat distanceFromBottom = scrollView.contentSize.height - contentYOffset;
    if (distanceFromBottom < height) {
        NSLog(@"底部");
        self.homePageTableView.bounces = NO;
    }
    if (contentYOffset == 0) {
        NSLog(@"顶部");
        self.homePageTableView.bounces = YES;
        
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//梅江林
-(void)getSuperSignInHttpData
{
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:@"%@%@",UserInfo,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"userInfo===%@",dic);
        if (dic) {
            
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:dic[@"user_profile"][@"avatar_url"] forKey:@"userHeadImage"];
            [user synchronize];
            
            
            
            if ([dic[@"last_sign"] isKindOfClass:[NSNull class]]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    ShowDaySignInViewController *vc=[ShowDaySignInViewController new];
                    vc.days=[NSString stringWithFormat:@"%@",dic[@"all_sign"]];
                    vc.dontGotoShowDaySignInViewController=^(BOOL isGo){
                        _gotoShowDaySignInViewController=isGo;
                    };
                    [self.navigationController pushViewController:vc animated:YES];
                });
                
            }else{
                NSString *str=[NSString stringWithFormat:@"%@",dic[@"last_sign"]];
                NSInteger days=[self getDays:str];
                if (days>0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ShowDaySignInViewController *vc=[ShowDaySignInViewController new];
                        vc.days=[NSString stringWithFormat:@"%@",dic[@"all_sign"]];
                        vc.dontGotoShowDaySignInViewController=^(BOOL isGo){
                            _gotoShowDaySignInViewController=isGo;
                        };
                        [self.navigationController pushViewController:vc animated:YES];
                    });
                }else{
                    
                }
                
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
    
    
}

-(NSInteger)getDays:(NSString *)str
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:2];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:str]];
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
    NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
    // dayComponents.day  即为间隔的天数
    NSLog(@"======%ld",dayComponents.day);
    return dayComponents.day;
}


/**
 *  是否可以打开设置页面
 *
 *  @return
 */
- (BOOL)canOpenSystemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

/**
 *  跳到系统设置页面
 */
- (void)systemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

//兑换优惠券
-(void)getQuan:(NSString *)codeStr
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    [self.view isLoading:YES];
    [manager POST:[NSString stringWithFormat:GetYouHuiQuan,token,codeStr] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"所有的优惠券%@",dic);
        if (dic[@"code"]==nil) {
            [self.view showTiShiMessage:@"优惠码无效"];
        }else{
            [self.view showTiShiMessage:@"兑换成功"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        NSLog(@"error%@",error.localizedDescription);
        [self.view showTiShiMessage:@"兑换码无效"];
    }];
    
}


@end
